import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/'
import { Dialog } from 'vant'

Vue.use(VueRouter)

// 路由表
const routes = [
  {
    path: '/login',
    name: 'login',
    meta: { requiresAuth: false },
    component: () => import('@/views/login/')
  },
  {
    path: '/',
    component: () => import('@/views/layout/'),
    children: [
      {
        path: '', // 默认子路由 home
        name: 'home',
        meta: { requiresAuth: false },
        component: () => import('@/views/home/')
      },
      {
        path: 'qa',
        name: 'qa',
        meta: { requiresAuth: false },
        component: () => import('@/views/qa/')
      },
      {
        path: '/video',
        name: 'video',
        meta: { requiresAuth: false },
        component: () => import('@/views/video/')
      },
      {
        path: '/profile',
        name: 'profile',
        meta: { requiresAuth: false },
        component: () => import('@/views/profile/')
      }
    ]
  },
  {
    path: '/search',
    component: () => import('@/views/search/')
  },
  {
    path: '/article/:articleId',
    name: 'article',
    meta: { requiresAuth: false },
    component: () => import('@/views/article/'),
    // 开启组件 props ,映射到组件中
    props: true
  },
  {
    path: '/user/profile',
    meta: { requiresAuth: true },
    component: () => import('@/views/user-profile/')
  },
  {
    path: '/user/chat',
    meta: { requiresAuth: true },
    component: () => import('@/views/user-chat/')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    const user = store.state.user
    if (user) {
      next()
    } else {
      Dialog.confirm({
        title: '温馨提示',
        message: '该功能需要登录才能访问, 确认要登录吗?',
        confirmButtonText: '去登录',
        cancelButtonText: '取消'
      }).then(() => {
        // on confirm
        router.push({
          name: 'login',
          query: {
            redirect: router.currentRoute.fullPath
          }
        })
      }).catch(() => {
        // on cancel
        next(false) // 取消了, 中断路由导航
      })
    }
  } else {
    // 不需要登录的页面直接过去
    next()
  }
})

export default router
